<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="800px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm, FormSchema } from '@/components/Form';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';

  import { createUser, updateUser } from '@/api/user'
  import { getRoleList } from '@/api/role'

  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(false);
  const id = ref();

  const schemas: FormSchema[] = [
    {
      field: 'name',
      label: '姓名',
      component: 'Input',
      required: true,
    },
    {
      field: 'username',
      label: '账号',
      component: 'Input',
      required: true,
      dynamicDisabled: () => {
        return !!isUpdate.value;
      },
    },
    {
      field: 'password',
      label: '密码',
      component: 'InputPassword',
      required: true,
      ifShow: () => {
        return !isUpdate.value;
      },
    },
    {
      field: 'role_ids',
      label: '角色',
      component: 'ApiSelect',
      componentProps: {
        value: '3',
        mode: 'multiple',
        api: getRoleList,
        resultField: 'items',
        labelField: 'name',
        valueField: 'id',
        immediate: true,
        allowClear: true,
      },
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 24 },
    schemas: schemas,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    isUpdate.value = data?.isUpdate;
    console.log(isUpdate.value);
    id.value = data?.record?.id;
    resetFields();
    setDrawerProps({ confirmLoading: false });
    if (unref(isUpdate)) {
      setFieldsValue({
        ...data.record,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增用户' : '编辑用户'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });

      if (unref(isUpdate)) {
        await updateUser(id.value, values);
      } else {
        await createUser(values);
      }
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>